package models

import (
	"github.com/beego/beego/v2/client/orm"
	"weiboxs.com/new_h_glasses/utils"
)

type ErpEntryData struct {
	Id           int64
	Entry        *ErpEntry    `orm:"rel(fk);null;on_delete(do_nothing)"`
	Products     *ErpProducts `orm:"rel(fk);null;on_delete(do_nothing)"`
	InventoryId  int64 //库存ID
	Snd          *ErpProductsSnd `orm:"rel(fk);null;on_delete(do_nothing)"`
	Amount       int64           `json:"purchase_num"`
	StorageNum   int64           `json:"storage_num"`
	UnitPrice    float64
	Diopter      string `json:"sph" orm:"-"` //屈光度
	Astigmatism  string `json:"cyl" orm:"-"` //散光度
	Addlight     string `json:"add" orm:"-"` //下加光
	ModelNumber  string `orm:"-"`
	ColourNumber string `orm:"-"`
	Size         string `orm:"-"` //尺寸
	Genre        string `orm:"-"` //框形
	FilmColor    string `orm:"-"` //膜层颜色
	FunctionInfo string `orm:"-"` //功效
	SndId        int64  `orm:"-"` //SNDID
	SmallPlan    float64
	MiddleId     int64 //中间表ID
	Remarks      string
}

//查询
type ErpEntryDataQueryParam struct {
	BaseQueryParam
	StartDate  string `json:"start_date"`
	EndDate    string `json:"end_date"`
	EntryNo    string `json:"entry_no"`
	Depid      int64  `json:"depid"`
	Suppliers  string `json:"suppliers"`
	Auditing   int    `json:"auditing"`
	Typeid     []int
	RelatedSel []interface{}
}

func (a *ErpEntryData) TableName() string {
	return ErpEntryDataTableName()
}

func ErpEntryDataTableName() string {
	return TableName("erp_entry_data")
}

func ErpEntryDataPageList(params *ErpEntryDataQueryParam) ([]*ErpEntryData, int64) {

	ls := make([]*ErpEntryData, 0)

	query := orm.NewOrm().QueryTable(ErpEntryDataTableName()).RelatedSel(params.RelatedSel...)

	cond := orm.NewCondition()

	if len(params.StartDate) > 0 {
		cond = cond.And("Entry__CreatedAt__gte", utils.GetDateParse(params.StartDate))
	}
	if len(params.EndDate) > 0 {
		cond = cond.And("Entry__CreatedAt__lte", utils.GetDateParse(params.EndDate)+68400)
	}
	if len(params.EntryNo) > 0 {
		cond = cond.And("Entry__Number", params.EntryNo)
	}
	if len(params.Suppliers) > 0 {
		cond = cond.And("Products__Suppliers__Id", params.Suppliers)
	}
	if len(params.Typeid) > 0 {
		cond = cond.And("Products__TypeId__in", params.Typeid)
	}
	if params.Depid > 0 {
		cond = cond.And("Entry__DepartmentId", params.Depid)
	}
	if params.Auditing > 0 {
		cond = cond.And("Entry__Auditing", params.Auditing)
	}

	query = query.SetCond(cond)

	sortorder := "-Id"

	switch params.Sort {
	case "Id":
		sortorder = "Id"
	}
	if params.Order == "desc" {
		sortorder = "-" + sortorder
	}

	total, _ := query.Count()

	query.OrderBy(sortorder).Limit(params.Limit, params.Offset).All(&ls)

	return ls, total
}

func ErpEntryDataList(entryId int64) []*ErpEntryData {
	list := make([]*ErpEntryData, 0)
	o := orm.NewOrm().QueryTable(ErpEntryDataTableName()).RelatedSel()
	o.All(&list)
	return list
}

func ErpEntryDataAdd(c *ErpEntryData) (int64, error) {

	return orm.NewOrm().Insert(c)
}
